package com.bluetrum.devicemanager.cmd.payloadhandler;

import androidx.annotation.NonNull;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public abstract class TlvPayloadHandler<T> extends PayloadHandler<T>{

    public TlvPayloadHandler(@NonNull byte[] payload) {
        super(payload);
    }

    protected Map<Byte, byte[]> getTlvEntries() {
        final HashMap<Byte, byte[]> map = new HashMap<>();

        ByteBuffer bb = ByteBuffer.wrap(getPayload());
        while (bb.remaining() >= 3) {
            byte t = bb.get();
            byte l = bb.get();
            if (l > bb.remaining()) {
                // 格式错误
                return null;
            }
            byte[] v = new byte[l];
            bb.get(v);
            map.put(t, v);
        }
        if (map.size() > 0)
            return map;

        return null;
    }
}
